package com.wan37.logic.utils;

import com.wan37.logic.component.LogicWorkerHandlerCenter;
import com.wan37.logic.handler.WorkerHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 延迟队列池工具
 *
 * @author : luoyong
 * @date : 2020-06-03 18:26
 **/
@Component
public class DelayDequeThreadPollUtil {

    /**
     * 逻辑处理中心
     */
    @Autowired
    private LogicWorkerHandlerCenter logicWorkerHandlerCenter;

    /**
     * 保存启动延迟任务的返回对象，便于后期停止等操作
     */
    private final Map<String, ScheduledFuture> stringScheduledFutureMap = new HashMap<>();

    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(10, (r) -> {
        Thread t = new Thread(r);
        t.setName("后台延迟线程:");
        t.setDaemon(true);
        return t;
    });

    /**
     * 设置初始启动时间的循环延迟队列
     *
     * @param initialDelay
     * @param delay
     * @param roleId
     * @param sceneId
     * @param workerHandler
     */
    public void updateTimeWithFixedDelay(long initialDelay, long delay, String roleId, String sceneId, WorkerHandler workerHandler) {
        //启动任务
        ScheduledFuture<?> self = service.scheduleWithFixedDelay(() -> logicWorkerHandlerCenter.distributeWork(sceneId, workerHandler)
                , initialDelay, delay, TimeUnit.SECONDS);

        stringScheduledFutureMap.put(getScheduledFutureMapKey(roleId, workerHandler.getClass().getSimpleName()), self);
    }

    /**
     * 普通延迟队列
     *
     * @param delay         单位是秒
     * @param roleId
     * @param sceneId
     * @param workerHandler
     */
    public void updateTimeSchedule(long delay, String roleId, String sceneId, WorkerHandler workerHandler) {
        ScheduledFuture<?> self = service.schedule(() -> logicWorkerHandlerCenter.distributeWork(sceneId, workerHandler),
                delay, TimeUnit.SECONDS);
    }

    /**
     * 循环延迟队列的停止
     *
     * @param s
     */
    public void stop(String s) {
        if (stringScheduledFutureMap.containsKey(s)) {
            int i = 0;
            while (!stringScheduledFutureMap.get(s).cancel(true)) {
                i++;
                if (i > 10) {
                    break;
                }
            }
            System.out.println("循环延迟队列的停止成功！！");
        }
    }

    public String getScheduledFutureMapKey(String roleId, String workName) {
        return roleId + "-" + workName;
    }
}
